﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DepartmentOnline.Models;

namespace DepartmentOnline
{
    public partial class Group : System.Web.UI.Page
    {
        private int CurrentID;
        public string CurrentName;
        public DepartmentOnline.Models.Group CurrentGroup;
        protected void Page_Load(object sender, EventArgs e)
        {
            CurrentGroup = new DepartmentOnline.Models.Group();
            if (!IsPostBack)
            {
                if (Session["GroupID"] != null)
                {
                    CurrentID = Convert.ToInt32(Session["GroupID"]);
                    using (var context = new departmentEntities())
                    {
                        var group = context.Groups.Where(x => x.Id == CurrentID);
                        var firstOrDefault = group.FirstOrDefault();
                        if (firstOrDefault != null)
                        {
                            CurrentName = firstOrDefault.Number;
                            CurrentGroup = firstOrDefault;
                            lbDescription.Text = CurrentGroup.StudentsQty + " студентов";
                            context.Students.Where(x => x.Group.Id == CurrentGroup.Id).Load();
                            StudentsGrid.DataSource = context.Students.Local;
                            StudentsGrid.DataBind();
                            if (firstOrDefault.Plan != null)
                            {
                                DropDownList1.SelectedValue = Convert.ToString(firstOrDefault.Plan.Id);
                            }
                        }
                    }
                }
            }
            else
            {

            }
        }

        protected void UpdatePlan_Click(object sender, EventArgs e)
        {
            try
            {
                using (var context = new departmentEntities())
                {
                    var group = context.Groups.FirstOrDefault(x => x.Id == CurrentID); 
                    if (group != null)
                    {
                        var plan =
                            context.Plans.FirstOrDefault(x => x.Id == Convert.ToInt32(DropDownList1.SelectedValue));
                        if (plan != null) plan.Group = group;
                        context.SaveChanges();
                    }
                }

            }catch
            {
                
            }
        }
    }
}